//
//  SEGAdvlistManager.m
//  Commom
//
//  Created by 山刘 on 2019/4/2.
//  Copyright © 2019年 山刘. All rights reserved.
//

#import "SEGAdvlistManager.h"
#if __has_include(<Commom/SEGModel.h>)
#import <Commom/SEGModel.h>
#else
#import "SEGModel.h"
#endif

#if __has_include(<Commom/SEGHTTPBusinessManager.h>)
#import <Commom/SEGHTTPBusinessManager.h>
#else
#import "SEGHTTPBusinessManager.h"
#endif

#if __has_include(<Commom/SEGProfileManager.h>)
#import <Commom/SEGProfileManager.h>
#else
#import "SEGProfileManager.h"
#endif

//弹出广告本地缓存key值，用于获取、保存开启广告的记录
#define kUserDefaultPopWindowAdvertisement @"SEGUserDefaultPopWindowAdvertisement"

static id _advlistManager;
static dispatch_once_t onceToken;

@implementation SEGAdvlistManager
+(instancetype)sharedManager{
    dispatch_once(&onceToken, ^{
        _advlistManager = [[self alloc] init];
    });
    return _advlistManager;
}

+(void)destroyResource{
    onceToken = 0;
    _advlistManager = nil;
}

-(void)segRequestAdvlistWithPositionType:(SEGAdvlistType)position completed:(void(^)(BOOL isSuccessed,id result,NSString* codeType,NSString* errorMessage))completed{
    
    NSDictionary* params = @{@"positionType" : @(position)};
    
    __block NSInteger _positionType = position;
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/uhomecp-app/advertising/advlist.json",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:POST URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (!isSuccessed) {
            completed(isSuccessed,result,codeType,errorMessage);
            return;
        }
        
        if(![[result valueForKey:@"data"] isKindOfClass:[NSArray class]]){
            completed(NO,result,codeType,errorMessage);
            return;
        }
        
        NSMutableArray<SEGAdvertismentModel*> *arrM = [NSMutableArray array];
        for (NSDictionary *object in [result valueForKey:@"data"]) {
            SEGAdvertismentModel *data =[SEGAdvertismentModel yy_modelWithDictionary:object];
            if(data.position.integerValue == _positionType){
                [arrM addObject:data];
            }
        }
        
        self.advertis = [NSArray arrayWithArray:arrM];
        
        //if (position == SEGAdvlistType_SERVER) [self segSaveAdvertisementWithPostion:position forDataSource:self.advertis];
        [self segSaveAdvertisementWithPostion:position forDataSource:self.advertis];
        completed(isSuccessed,[NSArray arrayWithArray:arrM],codeType,errorMessage);
    }];
}

/**
 * 保存广告到本地路径
 * @author Sam
 */
-(BOOL)segSaveAdvertisementWithPostion:(SEGAdvlistType)position forDataSource:(NSArray<SEGAdvertismentModel*>*)dataSource{
    if (!dataSource || dataSource.count <= 0){
        return [NSKeyedArchiver archiveRootObject:[NSArray array] toFile:[self segAdvertisementLocalPath:position]];
    }
    return [NSKeyedArchiver archiveRootObject:dataSource toFile:[self segAdvertisementLocalPath:position]];
}

/**
 * 保存广告到本地路径
 * @author Sam
 */
-(NSArray<SEGAdvertismentModel*>*)segGetAdvertisementWithPostion:(SEGAdvlistType)position{
    return [NSKeyedUnarchiver unarchiveObjectWithFile:[self segAdvertisementLocalPath:position]];
}

/**
 * 本地广告路径
 * @author Sam
 */
-(NSString*)segAdvertisementLocalPath:(SEGAdvlistType)position{
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    return [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"Advertisement%@%@Archiver.data",@(position).stringValue,kAccountUserID]];
    
}
/// 从本地获取当天的时间、用户ID、小区ID以格式：MM-dd,userId,communityID 数据
-(BOOL)segGetCurrentMonthAndDayAndUserIdAndCommunityIDToUserDefaults{
    NSString *time = [SEGUtils timeForTodayWithType:SEGSystemUtils_Time_Today_Type_Month_Day];
    NSString *record = [NSString stringWithFormat:@"%@,%@,%@",time,kAccountUserID,kAccountCommunityID];
    NSMutableArray *data = [[NSUserDefaults standardUserDefaults]objectForKey:kUserDefaultPopWindowAdvertisement];
    if (data && [data containsObject:record]) return NO;
    return YES;
}

/// 把当天的时间、用户ID、小区ID以格式：MM-dd,userId,communityID 保存到本地
-(void)segSaveCurrentMonthAndDayAndUserIdAndCommunityIDToUserDefaults{
    NSString *time = [SEGUtils timeForTodayWithType:SEGSystemUtils_Time_Today_Type_Month_Day];
    NSString *record = [NSString stringWithFormat:@"%@,%@,%@",time,kAccountUserID,kAccountCommunityID];
    
    //获取老数据
    NSMutableArray *oldData = [[NSUserDefaults standardUserDefaults]objectForKey:kUserDefaultPopWindowAdvertisement];
    oldData = oldData ? oldData : [NSMutableArray array];
    
    NSMutableArray *newData = [NSMutableArray array];
    //保存当天记录
    [oldData enumerateObjectsUsingBlock:^(NSString*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if([[obj componentsSeparatedByString:@","].firstObject isEqualToString:time]) [newData addObject:obj];
    }];
    
    if(![newData containsObject:record]) [newData addObject:record];
    
    //保存数据
    [[NSUserDefaults standardUserDefaults]setObject:newData forKey:kUserDefaultPopWindowAdvertisement];
}

-(NSArray<SEGAdvertismentModel*> *)advertis{
    if (!_advertis) {
        _advertis = [[NSArray alloc]init];
    }
    return _advertis;
}
@end
